package com.example.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.gateway.config.UrlsProperties;
import com.example.gateway.utils.JWTUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局拦截器
 */
@Component
@RefreshScope
public class UserAuthGlobalFiter   implements GlobalFilter, Ordered {
    private Logger logger = LoggerFactory.getLogger(UserAuthGlobalFiter.class);
    @Autowired
    private UrlsProperties urlsProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getURI().getPath();

        String token = serverHttpRequest.getHeaders().getFirst("Authorization");
        MultiValueMap<String, String> queryParams = exchange.getRequest().getQueryParams();
        //不需要认证的路径，直接放行
        List<String> urls = urlsProperties.getUrls();
        logger.info("path:{}",path);
        logger.info("urls:{}",urls);
        if (urls.contains(path)) {
            return chain.filter(exchange);
        }
        //开始认证
        String username = String.valueOf(serverHttpRequest.getQueryParams().get("username"));
        logger.info("请求username:{}",username);
        if(StringUtils.isBlank(token))
        {
            //写法1
            //设置状态码 未授权401
            //exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            //个人理解,终止输出访问
            //return exchange.getResponse().setComplete();
            //写法2
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            response.setStatusCode(HttpStatus.FORBIDDEN);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            Map<String,Object> errorMsg = new HashMap<>();
            errorMsg.put("code",500);
            errorMsg.put("msg","无权限");
            String errorJSon  = JSON.toJSONString(errorMsg);
            DataBuffer dataBuffer = dataBufferFactory.wrap(errorJSon.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }

        //继续往下执行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 判断是否可以访问
     * @param urls
     * @return
     */
  /* public boolean isVisist(ServerWebExchange exchange, GatewayFilterChain chain,List<String>urls){
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        //当前请求的路径
        String path = serverHttpRequest.getURI().getPath();
        //请求的路径存在与携带的路径中，那就允许访问
        if (null == urls || urls.size()<=0){
            return false;
        }
        //遍历，如果找到相同的路径就返回true
       for (String s:urls){
           if (s.equals(path)){
               return true;
           }
       }
       return false;
    }*/
}
